package com.yunkss.eftool.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.reactor.context.SaReactorSyncHolder;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.yunkss.eftool.business.result.EfResult;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.RequestPath;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;

/**
 * @Author csx
 * @Date 2024/4/23 9:15
 * @Description TODO  EfTokenConfig
 **/
@Configuration
public class EfTokenConfig {

    /**
     * 注册 [Sa-Token全局过滤器]
     */
    @Bean
    public SaReactorFilter getSaReactorFilter() {
        return new SaReactorFilter()
                // 指定 [拦截路由]
                .addInclude("/**")    /* 拦截所有path */
                // 指定 [放行路由]
                .addExclude("/favicon.ico")
                .setAuth(obj -> {
                    RequestPath path = SaReactorSyncHolder.getContext().getRequest().getPath();
                    //示例暂时只校验是否登录
                    SaRouter.match("/**").notMatch(Arrays.asList(new String[]{"/api/404","/404","/api/401","/401","/api/eftool/login", "/eftool/login", "/api/eftool/upload", "/eftool/upload", "/api/eftool/download/*", "/eftool/download/*"})).check(StpUtil::checkLogin);
                })
                .setError(e -> {
                    ServerWebExchange exchange = SaReactorSyncHolder.getContext();
                    exchange.getResponse().getHeaders().set("Content-Type", "application/json;charset=utf-8");
                    if (e instanceof NotLoginException) {
                        return JSONObject.toJSONString(EfResult.fail("332211", "请先登录后再进行操作~"));
                    }
                    return JSONObject.toJSONString(EfResult.fail("445567", "请求错误,原因为:" + e.getMessage()));
                })
                ;
    }

}
